<template>
  <div ref="containerRef" class="container"/>
</template>

<script lang="ts">
import {defineComponent, onMounted, onUnmounted, useTemplateRef, watch} from 'vue';
import * as THREE from 'three';
import {ThreeFramework} from "@/utils/ThreeFramework";

export default defineComponent({
  name: 'Base3DComponent',
  props: {
    width: {
      type: Number,
      default: 1,
    },
    height: {
      type: Number,
      default: 1,
    },
    depth: {
      type: Number,
      default: 1,
    },
    color: {
      type: String,
      default: '#00ff00',
    },
  },
  setup(props) {
    const containerRef = useTemplateRef<HTMLDivElement>('containerRef');
    let renderer: THREE.WebGLRenderer;
    let scene: THREE.Scene;
    let camera: THREE.PerspectiveCamera;
    let framework: ThreeFramework;
    let cube: THREE.Mesh;
    const init = () => {
      if (!containerRef.value){
        return;
      }
      framework = new ThreeFramework(containerRef.value, window.innerWidth, window.innerHeight);
      const geometry = new THREE.BoxGeometry(props.width, props.height, props.depth);
      const material = new THREE.MeshBasicMaterial({color: props.color});
      cube = new THREE.Mesh(geometry, material);
      framework.addMesh(cube);
      framework.start();
      const animate = () => {
        requestAnimationFrame(animate);
        if (cube) cube.rotation.x += 0.01;
        if (cube) cube.rotation.y += 0.01;
        if (renderer) renderer.render(scene, camera);
      };
      animate();
    };

    onMounted(() => {
      if (containerRef?.value) {
        init();
      }
    });

    onUnmounted(() => {
      if (renderer) {
        renderer.dispose();
      }
    });
    return {
      containerRef,
    };
  },
});
</script>

<style scoped>
.container {
  width: 100%;
  height: 100%;
}
</style>